package com.xiaoyu.lanling.feature.privilege

import android.os.Bundle
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.lanling.feature.privilege.data.PrivilegeSetting
import com.xiaoyu.lanling.event.privilege.PrivilegeSettingEvent
import com.xiaoyu.lanling.event.privilege.PrivilegeSettingSyncEvent
import com.xiaoyu.lanling.feature.user.model.UserExtra
import kotlinx.android.synthetic.main.activity_privilege_settting.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class PrivilegeSettingActivity : AppCompatToolbarActivity() {

    private val requestTag = Any()

    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        setLightStatusBar()
        setContentView(R.layout.activity_privilege_settting)
        initToolbar()

        initView()
        initBind()
        initEvent()
        initData()
    }

    private fun initView() {
        setTitle(R.string.vip_privilege)
        updateUi()
    }

    private fun initBind() {
        hide_distance_choice.setOnCheckedChangeListener { buttonView, isChecked ->
            PrivilegeSetting.setPrivilege(requestTag, isChecked, UserExtra.instance.hideVisit)
        }

        hide_footprint_choice.setOnCheckedChangeListener { buttonView, isChecked ->
            PrivilegeSetting.setPrivilege(requestTag, UserExtra.instance.hideDistance, isChecked)
        }
    }

    private fun initData() {
        PrivilegeSetting.getPrivilegeSetting(requestTag)
    }

    private fun updateUi() {
        hide_distance_choice.isChecked = UserExtra.instance.hideDistance
        hide_footprint_choice.isChecked = UserExtra.instance.hideVisit
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: PrivilegeSettingSyncEvent) {
                UserExtra.instance.updatePrivilegeSetting(event.hideDistance, event.hideVisit)
                updateUi()
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: PrivilegeSettingEvent) {
                UserExtra.instance.updatePrivilegeSetting(event.hideDistance, event.hideVisit)
                //NOTE prevent event loop , so do not update switch state
//                updateUi()
            }
        })
    }
}